package eiisan.function;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

/**
 * 归并算法
 * @author eii
 * @sice 2020/11/13
 */
public class MergeSortDemo {

    public static void main(String[] args) {
        Integer[] a1 = {1, 2, 4, 4, 15, 46, 67, 78, 79};
        Integer[] a2 = {3, 12, 24, 25, 25, 36, 47, 48, 99};
        Integer[] a3 = {33, 42, 44, 85, 95, 123, 147, 148, 299};
        List<Integer> sort = sort(a1,a2,a3);
        System.out.println(sort);
    }

    public static List<Integer> sort(Integer[]... arrs) {
        List<Integer> res = new ArrayList<>();
        if (arrs == null || arrs.length == 0)
            return res;
        PriorityQueue<Node> priorityQueue = new PriorityQueue<>(arrs.length, Comparator.comparing(t -> t.arr[t.idx]));
        for (Integer[] arr : arrs) {
            if (arr == null || arr.length == 0) continue;
            Node node = new Node(arr, 0);
            priorityQueue.offer(node);
        }

        while (!priorityQueue.isEmpty()) {
            Node poll = priorityQueue.poll();
            res.add(poll.arr[poll.idx]);
            if (poll.idx < poll.arr.length - 1)
                priorityQueue.add(new Node(poll.arr, poll.idx + 1));
        }
        return res;
    }

    private static class Node {
        private Integer[] arr;
        private int idx;

        public Node() {
        }

        public Node(Integer[] arr, int idx) {
            this.arr = arr;
            this.idx = idx;
        }
    }
}
